#include "CsvParser.h"

#include <QTextStream>
#include <QStringList>

static const QChar c_Comma(',');

CsvParser::CsvParser() :
    m_StaticGSOIDs(),
    m_StaticGSOIDsRegExp(),
    m_StaticGSOIDsVsAttributes(),
    m_TopRow()
{
}

void CsvParser::ParseFile(QFile &rFile)
{
    if (!rFile.isOpen())
    {
        return;
    }

    Reset_();
    QTextStream In(&rFile);

    // Skip first line, it should contain a header row,
    // something like:
    // Static GSOID, Atribute ID
    if (!In.atEnd())
    {
        m_TopRow = In.readLine();
    }

    /**
      * @warning
      *
      * I assume that there is only one comma, cause we have two columns:
      * Static GSOID and Attribute ID, eg.:
      *
      * GSOID,Attribute ID,Attribute Access
      * 1:1,2,Read_Only
      */
    QStringList SplitLine;

    while (!In.atEnd())
    {
        QString Line = In.readLine();
        SplitLine = Line.split(c_Comma);

        QString GSOID = SplitLine.at(0);
        QString AttributeID = SplitLine.at(1);
        QString Access = SplitLine.at(2);

        if (!m_StaticGSOIDs.contains(GSOID))
        {
            m_StaticGSOIDs.append(GSOID);
        }

        m_StaticGSOIDsVsAttributes.insertMulti(
            GSOID, qMakePair(AttributeID, Access));
    }

    m_StaticGSOIDsRegExp = m_StaticGSOIDs;

    QVector<QString>::iterator it = m_StaticGSOIDsRegExp.begin();
    for (; it != m_StaticGSOIDsRegExp.end(); ++it)
    {
        it->prepend('^');
        it->replace(":0", ":\\d+");
        it->append('$');
    }
}

void CsvParser::Reset_()
{
    m_StaticGSOIDs.clear();
    m_StaticGSOIDsVsAttributes.clear();
    m_StaticGSOIDsRegExp.clear();
}
